package org.example.readwritelock;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.Sleeper;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁使用
 * 提供一个 数据容器类，其内部分别使用
 * - 读锁保护数据的 `read()`方法
 * - 写锁保护数据的 `write()`方法
 * @author ZhengDp
 * @Date 2023/1/15 22:51
 */
@Slf4j(topic = "c.DataContainer")
public class DataContainer {
    private int data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    // 读锁
    private ReentrantReadWriteLock.ReadLock r = rw.readLock();
    // 写锁
    private ReentrantReadWriteLock.WriteLock w = rw.writeLock();


    public Object read(){
        log.info("获取读锁...");
        r.lock();
        try{
            log.info("读取");
            Sleeper.sleep(1000);
            return data;
        }finally {
            log.info("释放读锁...");
            r.unlock();
        }
    }

    public void write(){
        log.info("获取写锁...");
        w.lock();
        try{
            log.info("写入");
            Sleeper.sleep(1000);
        }finally {
            log.info("释放写锁...");
            w.unlock();
        }

    }

    public static void main(String[] args) {
        DataContainer container = new DataContainer();
        new Thread(() -> {
            container.read();
        },"t1").start();
        Sleeper.sleep(100);
        new Thread(() -> {
            container.write();
        },"t2").start();
    }
}
